<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools title="总记录20条">
        <el-button
          v-if="$store.state.user.userInfo.roles.points.includes('import_excel')"
          type="warning"
          size="small"
          @click="$router.push('/import')"
        >excel导入</el-button>
        <el-button
          v-if="$store.state.user.userInfo.roles.points.includes('import_excel')"
          type="danger"
          size="small"
          @click="hExportExcel"
        >excel导出</el-button>
        <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
      </PageTools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="employee" :default-sort="{prop: 'timeOfEntry'}">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" sortable label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" sortable label="入职时间" />
          <!-- <el-table-column prop="username" label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id )">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            :page-sizes="[2,5,10]"
            layout="total,sizes, prev, pager, next"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="添加"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <EmpDialog ref="empDialog" @success="hSuccess" />
    </el-dialog>

    <el-dialog :visible.sync="showDialogRole">
      <AssignRole v-if="showDialogRole" :cur-id="curId" @success="hSuccessRole" />
    </el-dialog>
  </div>
</template>
<script>
// import  PageTools  from '@/components/PageTools/index.vue'
import { TYPE_MAP } from '@/constant/index'
import { getEmployee, delEmployee } from '@/api/empoyees'
import EmpDialog from './EmpDialog.vue'
import AssignRole from './AssignRole.vue'
export default {
  components: { EmpDialog, AssignRole },
  data() {
    return {
      employee: [],
      total: 0,
      size: 2,
      page: 1,
      showDialog: false, // 添加员工
      showDialogRole: false, // 设置角色
      // 保存
      curId: '' // 当前员工的id
    }
  },
  created() {
    this.loadEmployee()

    setTimeout(() => {
      this.$i18n.locale = 'zh'
    }, 3000)
  },
  methods: {
    // 子组件角色保存成功
    hSuccessRole() {
      this.showDialogRole = false
      this.$message.success('保存成功')
    },
    hAssign(id) {
      this.showDialogRole = true
      // 2.保存id
      this.curId = id
    },
    // rows: [{mobile:'13600000001', usename:'吕勇锐'}, {mobile:'13600000002', usename:'袁永安'}]
    //
    // data:
    //  [
    //   ["13600000001", "吕勇锐"]
    //   ["13600000002", "袁永安"]
    //  ]
    formatData(rows) {
      // 表头
      const header = Object.keys(rows[0])
      // 内容
      const data = rows.map(obj => { return Object.values(obj) })

      return { header, data }
    },
    async hExportExcel() {
      // 1. 发请求拿数据
      const res = await getEmployee({ page: this.page, size: this.size })
      // 2. 对数据进行格式转换
      const { header, data } = this.formatData(res.data.rows)
      // 3. 导出
      console.log('员工信息', header, data)

      import('@/vendor/Export2Excel').then(excel => {
        // 准备数据
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)

        // 生成excel
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    hSuccess() {
      console.log('子组件添加成功')
      this.showDialog = false
      this.loadEmployee()
    },
    async doDel(id) {
      await delEmployee(id)
      if (this.employee.length === 1) {
        if (this.page > 1) {
          this.page--
        }
      }
      this.$message.success('删除成功')
      this.loadEmployee()
    },
    hDel(id) {
      this.$confirm('确认要删除', '系统的提示').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    // 每页几条
    hSizeChange(curPageSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.size = curPageSize
      this.page = 1
      // 2. 重发请求
      this.loadEmployee()
    },
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployee()
    },
    format(type) {
      return TYPE_MAP[type] || '未知'
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployee(this.page, this.size)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },

    async loadEmployee() {
      const res = await getEmployee({ page: this.page, size: this.size })
      this.employee = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
